package com.sandy.demo.controller;

import com.sandy.demo.jpa.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController()
public class AuthController {
    @Autowired
    AuthUserRepository userRepo;

    @Autowired
    AuthRoleRepository roleRepo;

    @Autowired
    AuthPermissionRepository permRepo;

    @Autowired
    PasswordEncoder passwordEncoder;

    @GetMapping("/init")
    String initAuthorization() {
        AuthRole adminRole = roleRepo.findFirstByRoleId("ADMIN");
        if (adminRole == null) {
            adminRole = new AuthRole();
            adminRole.setRoleId("ADMIN");
            adminRole.setRoleName("管理员");
            roleRepo.save(adminRole);
        }
        AuthRole userRole = roleRepo.findFirstByRoleId("USER");
        if (userRole == null) {
            userRole = new AuthRole();
            userRole.setRoleId("USER");
            userRole.setRoleName("普通用户");
            roleRepo.save(userRole);
        }
        if (!permRepo.existsByPermissionName("canSee")) {
            AuthPermission permission = new AuthPermission();
            permission.setPermissionName("hello");
            permission.setUrl("api/canSee");
            permission.getRoles().add(adminRole);
            permRepo.save(permission);
        }
        if (!userRepo.existsByUsername("sandy")) {
            AuthUser user = new AuthUser();
            user.setUsername("sandy");
            user.setPassword(passwordEncoder.encode("123456"));
            user.getRoles().add(adminRole);
            userRepo.save(user);
        }
        if (!userRepo.existsByUsername("user")) {
            AuthUser user = new AuthUser();
            user.setUsername("user");
            user.setPassword(passwordEncoder.encode("123456"));
            user.getRoles().add(userRole);
            userRepo.save(user);
        }
        return "ok";
    }

    @GetMapping("/canSee")
    String canSee() {
        return "see me";
    }

    @GetMapping("/login")
    public ResponseEntity<?> refreshAndGetAuthenticationToken(
            @RequestParam String username,
            @RequestParam String password) throws AuthenticationException {
        return ResponseEntity.ok(username);
    }
}
